// pages/home/home.ts
const api = require('../../config/api.js');
const util = require('../../utils/util.js');

interface TabItem {
  name: string;
  icon: string;
}

interface FilterItem {
  text: string;
  arrow: string;
}

interface CarpoolCard {
  id: string; // 添加ID字段
  tripType: 'outbound' | 'return';
  tripTypeText: string;
  serviceType: string;
  tripTime: string;
  startLocation: string;
  endLocation: string;
  userAvatar: string;
  userName: string;
  status: string;
  peopleCount: string;
  boardCount: string;
  bagCount: string;
  price: string;
  peopleIcon: string;
  boardIcon: string;
  bagIcon: string;
  isClub: number; // 添加isClub字段
}

interface NavItem {
  name: string;
  icon: string;
}

interface CarpoolRequest {
  /**
   * 地址编号，地址列表接口返回
   */
  address?: number;
  /**
   * 时间
   */
  beginTime?: string;
  endTime?: string;
  /**
   * 0:前往  1:返回
   */
  side?: number;
  /**
   * 0:车找人 1:人找车
   */
  type?: number;
  [property: string]: any;
}

interface CarpoolItem {
  id: string;
  side: number;
  date: string;
  goTime?: string; // 出发时间，格式 HH:mm
  type: number;
  fromAddr: string;
  toAddr: string;
  isClub: number;
  nickName: string;
  people: number;
  ski: number;
  bag: number;
  price: number;
  imageUrl: string;
}

interface CarpoolResponse {
  code: string;
  msg: string;
  data: {
    carList: CarpoolItem[];
  };
}

interface HomePageData {
  activeTab: number;
  activeNav: number;
  showDrawer: boolean;
  showTripSelector: boolean;
  selectedTrip: 'outbound' | 'return'; // TripSelector 选择状态
  tabs: TabItem[];
  filters: FilterItem[];
  carpoolCards: CarpoolCard[];
  navItems: NavItem[];
  loading: boolean;
  carpoolRequest: CarpoolRequest;
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 0,
    activeNav: 0,
    showDrawer: false,
    showTripSelector: false,
    selectedTrip: 'outbound' as 'outbound' | 'return', // TripSelector 默认选择
    loading: false,
    carpoolRequest: {
      address: undefined,
      beginTime: undefined,
      endTime: undefined,
      side: undefined,
      type: undefined
    },
    tabs: [
      {
        name: '拼车',
        icon: 'https://static.codia.ai/image/2025-10-08/sxMkNvyYsa.png'
      },
      {
        name: '拼房',
        icon: 'https://static.codia.ai/image/2025-10-08/5SYyvbuxDb.png'
      },
      {
        name: '雪票',
        icon: 'https://static.codia.ai/image/2025-10-08/hLATZd8zmW.png'
      }
    ],
    filters: [
      {
        text: '类型',
        arrow: 'https://static.codia.ai/image/2025-10-08/xv6kLuGdSQ.png'
      },
      {
        text: '往返',
        arrow: 'https://static.codia.ai/image/2025-10-08/7zwhU1NJWV.png'
      },
      {
        text: '雪场',
        arrow: 'https://static.codia.ai/image/2025-10-08/uP1qSWkZm6.png'
      },
      {
        text: '日期',
        arrow: 'https://static.codia.ai/image/2025-10-08/ssEap6ePBe.png'
      }
    ],
    carpoolCards: [
      {
        tripType: 'outbound',
        tripTypeText: '前往',
        serviceType: '车找人',
        tripTime: '后天 周六 10:00',
        startLocation: '北京市朝阳区石佛营中水金海嘉苑(石佛营东...',
        endLocation: '云顶滑雪场',
        userAvatar: 'https://static.codia.ai/image/2025-10-08/z0ouKB6QcC.png',
        userName: '昵称文字',
        status: '可拼',
        peopleCount: '1人',
        boardCount: '1板',
        bagCount: '1板包',
        price: '113',
        peopleIcon: 'https://static.codia.ai/image/2025-10-08/L2juZcsFLH.png',
        boardIcon: 'https://static.codia.ai/image/2025-10-08/8xYeG5naGc.png',
        bagIcon: 'https://static.codia.ai/image/2025-10-08/T41amkDiie.png'
      },
      {
        tripType: 'return',
        tripTypeText: '返回',
        serviceType: '人找车',
        tripTime: '09.25 10:00',
        startLocation: '北京市朝阳区石佛营中水金海嘉苑(石佛营东...',
        endLocation: '云顶滑雪场',
        userAvatar: 'https://static.codia.ai/image/2025-10-08/2oFbs4t1fL.png',
        userName: '昵称文字',
        status: '求拼',
        peopleCount: '1人',
        boardCount: '1板',
        bagCount: '1板包',
        price: '113',
        peopleIcon: 'https://static.codia.ai/image/2025-10-08/DGZcWdqAXv.png',
        boardIcon: 'https://static.codia.ai/image/2025-10-08/sR1Lra9YPF.png',
        bagIcon: 'https://static.codia.ai/image/2025-10-08/D0YJWoKXdu.png'
      },
      {
        tripType: 'return',
        tripTypeText: '返回',
        serviceType: '车找人',
        tripTime: '09.25 10:00',
        startLocation: '北京市朝阳区石佛营中水金海嘉苑(石佛营东...',
        endLocation: '云顶滑雪场',
        userAvatar: 'https://static.codia.ai/image/2025-10-08/rStSCj18HN.png',
        userName: '昵称文字',
        status: '求拼',
        peopleCount: '1人',
        boardCount: '1板',
        bagCount: '1板包',
        price: '113',
        peopleIcon: 'https://static.codia.ai/image/2025-10-08/1ZRuXzXbmm.png',
        boardIcon: 'https://static.codia.ai/image/2025-10-08/ewGb6vQdqA.png',
        bagIcon: 'https://static.codia.ai/image/2025-10-08/O9Qx6NuZQL.png'
      }
    ],
    navItems: [
      {
        name: '广场',
        icon: 'https://static.codia.ai/image/2025-10-08/F18Tngjj1L.png'
      },
      {
        name: '进阶',
        icon: 'https://static.codia.ai/image/2025-10-08/CqNGgrEjag.png'
      },
      {
        name: '发布',
        icon: 'https://static.codia.ai/image/2025-10-08/qbqH6hoyrt.png'
      },
      {
        name: '商城',
        icon: 'https://static.codia.ai/image/2025-10-08/6VQQBa08EF.png'
      },
      {
        name: '我的',
        icon: 'https://static.codia.ai/image/2025-10-08/KGLOQSy5JC.png'
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options?: Record<string, any>): void {
    console.log('Home页面加载完成', options);
    // 页面加载时获取拼车数据
    this.loadCarpoolData();
  },

  /**
   * 加载拼车数据
   */
  loadCarpoolData(): void {
    this.setData({
      loading: true
    });

    util.request(api.CarIndex, this.data.carpoolRequest, 'POST', 'application/json')
      .then((res: CarpoolResponse) => {
        console.log('拼车数据加载成功:', res);
        if (String(res.code) === '200' || String(res.code) === '0') {
          // 转换API数据为UI数据格式
          const carpoolCards = this.transformCarpoolData(res.data);
          this.setData({
            carpoolCards: carpoolCards,
            loading: false
          });
        } else {
          console.error('拼车数据加载失败:', res.msg);
          util.showErrorToast(res.msg || '数据加载失败');
          this.setData({
            loading: false
          });
        }
      })
      .catch((err: any) => {
        console.error('拼车数据请求失败:', err);
        util.showErrorToast('网络请求失败');
        this.setData({
          loading: false
        });
      });
  },

  /**
   * 格式化日期和时间（使用goTime字段）
   */
  formatDateWithTime(date: string | number, goTime?: string): string {
    if (!date) return "";

    try {
      // 判断是秒级时间戳还是毫秒级时间戳，或者是日期字符串
      let dateObj: Date;
      if (typeof date === 'string') {
        // 如果是日期字符串，如 "2024-01-01"
        dateObj = new Date(date);
      } else {
        dateObj = date < 10000000000
          ? new Date(date * 1000)
          : new Date(date);
      }

      // 验证日期是否有效
      if (isNaN(dateObj.getTime())) {
        return "";
      }

      const now = new Date();
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
      const dayAfterTomorrow = new Date(
        today.getTime() + 2 * 24 * 60 * 60 * 1000
      );

      const targetDate = new Date(
        dateObj.getFullYear(),
        dateObj.getMonth(),
        dateObj.getDate()
      );

      let prefix = "";
      if (targetDate.getTime() === today.getTime()) {
        prefix = "今天";
      } else if (targetDate.getTime() === tomorrow.getTime()) {
        prefix = "明天";
      } else if (targetDate.getTime() === dayAfterTomorrow.getTime()) {
        prefix = "后天";
      } else {
        const month = dateObj.getMonth() + 1;
        const day = dateObj.getDate();
        const dayNames = [
          "周日",
          "周一",
          "周二",
          "周三",
          "周四",
          "周五",
          "周六"
        ];
        const dayName = dayNames[dateObj.getDay()];
        // 如果有goTime，使用goTime；否则不显示时间
        if (goTime) {
          return `${month}.${day} ${dayName} ${goTime}`;
        }
        return `${month}.${day} ${dayName}`;
      }

      // 如果有goTime，使用goTime；否则使用从日期对象中提取的时间
      const timeStr = goTime || 
        `${dateObj.getHours().toString().padStart(2, "0")}:${dateObj.getMinutes().toString().padStart(2, "0")}`;
      return `${prefix} ${timeStr}`;
    } catch (error) {
      console.error("时间格式化失败:", error);
      return "";
    }
  },

  /**
   * 转换API数据为UI数据格式
   */
  transformCarpoolData(carList: CarpoolItem[]): CarpoolCard[] {
    return carList.map((item: CarpoolItem) => {
      return {
        id: item.id, // 保留原始ID，用于跳转详情页
        tripType: item.side === 0 ? 'outbound' : 'return',
        tripTypeText: item.side === 0 ? '前往' : '返回',
        serviceType: item.type === 0 ? '车找人' : '人找车',
        tripTime: this.formatDateWithTime(item.date, item.goTime),
        startLocation: item.fromAddr,
        endLocation: item.toAddr,
        userAvatar: item.imageUrl || 'https://static.codia.ai/image/2025-10-08/z0ouKB6QcC.png',
        userName: item.nickName,
        status: item.type === 0 ? '可拼' : '求拼',
        peopleCount: `${item.people}人`,
        boardCount: `${item.ski}板`,
        bagCount: `${item.bag}板包`,
        price: item.price.toString(),
        peopleIcon: 'https://static.codia.ai/image/2025-10-08/L2juZcsFLH.png',
        boardIcon: 'https://static.codia.ai/image/2025-10-08/8xYeG5naGc.png',
        bagIcon: 'https://static.codia.ai/image/2025-10-08/T41amkDiie.png',
        isClub: item.isClub // 添加isClub字段
      };
    });
  },

  /**
   * 更新拼车请求参数
   */
  updateCarpoolRequest(params: Partial<CarpoolRequest>): void {
    this.setData({
      carpoolRequest: {
        ...this.data.carpoolRequest,
        ...params
      }
    });
    // 重新加载数据
    this.loadCarpoolData();
  },

  /**
   * Tab切换事件 (Vant组件)
   */
  onTabChange(e: any): void {
    const activeTab = e.detail.name;
    this.setData({
      activeTab: activeTab
    });
    console.log('Tab切换:', activeTab);
  },

  /**
   * Tab点击事件
   */
  onTabClick(e: WechatMiniprogram.TouchEvent): void {
    const index = e.currentTarget.dataset.index as number;
    this.setData({
      activeTab: index
    });
    console.log('Tab点击:', this.data.tabs[index].name);
  },

  /**
   * 筛选器点击事件
   */
  onFilterClick(e: WechatMiniprogram.TouchEvent): void {
    const index = e.currentTarget.dataset.index as number;
    console.log('筛选器点击:', this.data.filters[index].text);
    
    wx.showToast({
      title: '筛选功能开发中',
      icon: 'none',
      duration: 2000
    });
  },

  /**
   * 添加按钮点击事件
   */
  onAddClick(): void {
    console.log('添加按钮点击');
    
    // 使用工具函数进行登录校验
    util.executeWithLoginCheck(
      () => {
        // 用户已登录，显示抽屉
        this.setData({
          showDrawer: true
        });
      },
      '发布拼车信息需要先登录，是否立即登录？',
      '/pages/home/home'
    );
  },

  /**
   * 关闭抽屉
   */
  onCloseDrawer(): void {
    this.setData({
      showDrawer: false
    });
  },

  /**
   * TripSelector 选择行程类型
   */
  selectTrip(e: WechatMiniprogram.TouchEvent): void {
    const tripType = e.currentTarget.dataset.trip as 'outbound' | 'return';
    console.log('选择行程类型:', tripType);
    
    this.setData({
      selectedTrip: tripType
    });
    
    // 可以在这里添加选择后的处理逻辑
    // 比如跳转到相应的发布页面
    if (tripType === 'outbound') {
      console.log('选择前往雪场');
      // 跳转到拼车发布页面
      wx.navigateTo({
        url: '/pages/carpoolAdd/carpoolAdd?side=0',
        success: () => {
          console.log('跳转到拼车发布页面成功');
        },
        fail: () => {
          console.log('跳转到拼车发布页面失败');
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    } else if (tripType === 'return') {
      console.log('选择雪场返回');
      // 跳转到拼车发布页面
      wx.navigateTo({
        url: '/pages/carpoolAdd/carpoolAdd?side=1',
        success: () => {
          console.log('跳转到拼车发布页面成功');
        },
        fail: () => {
          console.log('跳转到拼车发布页面失败');
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    }
    
    // 关闭抽屉
    this.setData({
      showDrawer: false
    });
  },

  /**
   * 关闭行程选择器
   */
  closeTripSelector(): void {
    this.setData({
      showTripSelector: false
    });
  },

  /**
   * 处理行程选择
   */
  handleTripSelected(trip: any): void {
    console.log('行程选择:', trip);
    this.setData({
      showTripSelector: false
    });
  },

  /**
   * 抽屉选项点击事件
   */
  onDrawerOptionClick(e: WechatMiniprogram.TouchEvent): void {
    const option = e.currentTarget.dataset.option as string;
    console.log('抽屉选项点击:', option);
    
    // 关闭抽屉
    this.setData({
      showDrawer: false
    });
    
    // 根据选项执行相应操作
    if (option === 'carpool') {
      wx.navigateTo({
        url: '/pages/carpoolAdd/carpoolAdd',
        success: () => {
          console.log('跳转到拼车信息新增页面成功');
        },
        fail: () => {
          console.log('跳转到拼车信息新增页面失败');
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    } else if (option === 'room') {
      wx.showToast({
        title: '拼房功能开发中',
        icon: 'none',
        duration: 2000
      });
    } else if (option === 'ticket') {
      wx.showToast({
        title: '雪票功能开发中',
        icon: 'none',
        duration: 2000
      });
    }
  },

  /**
   * 底部导航点击事件
   */
  onNavClick(e: WechatMiniprogram.TouchEvent): void {
    const index = e.currentTarget.dataset.index as number;
    console.log('导航点击:', this.data.navItems[index].name);
    
    wx.showToast({
      title: this.data.navItems[index].name + '功能开发中',
      icon: 'none',
      duration: 2000
    });
  },

  /**
   * 导航栏左侧点击事件
   */
  onClickLeft(): void {
    wx.navigateBack();
  },

  /**
   * Tabbar切换事件 (Vant组件)
   */
  onNavChange(e: any): void {
    const activeNav = e.detail;
    this.setData({
      activeNav: activeNav
    });
    console.log('底部导航切换:', activeNav);
  },

  /**
   * 卡片点击事件
   */
  onCardClick(e: WechatMiniprogram.TouchEvent): void {
    const index = e.currentTarget.dataset.index as number;
    const cardData = this.data.carpoolCards[index];
    
    console.log('点击拼车卡片:', cardData);
    
    if (!cardData || !cardData.id) {
      console.error('拼车卡片数据不完整:', cardData);
      wx.showToast({
        title: '数据错误',
        icon: 'none'
      });
      return;
    }
    
    // 跳转到拼车详情页
    const url = `/pages/carpoolDetail/carpoolDetail?id=${cardData.id}`;
    
    wx.navigateTo({
      url: url,
      success: () => {
        console.log('跳转到拼车详情页成功:', url);
      },
      fail: (err) => {
        console.error('跳转到拼车详情页失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady(): void {
    console.log('Home页面渲染完成');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow(): void {
    console.log('Home页面显示');
    
    // 检查是否从登录页面返回，如果是则显示抽屉
    this.checkLoginReturn();
  },

  /**
   * 检查是否从登录页面返回
   */
  checkLoginReturn(): void {
    const userInfo = wx.getStorageSync('userInfo');
    const token = wx.getStorageSync('token');
    const navUrl = wx.getStorageSync('navUrl');
    
    // 如果用户已登录且当前页面是目标页面，则显示抽屉
    if (userInfo && token && navUrl === '/pages/home/home') {
      console.log('用户登录成功返回，显示抽屉');
      // 清除导航URL
      wx.removeStorageSync('navUrl');
      // 显示抽屉
      this.setData({
        showDrawer: true
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide(): void {
    console.log('Home页面隐藏');
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload(): void {
    console.log('Home页面卸载');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh(): void {
    console.log('用户下拉刷新');
    // 重新加载拼车数据
    this.loadCarpoolData();
    // 停止下拉刷新
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom(): void {
    console.log('页面触底');
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(): WechatMiniprogram.Page.ICustomShareContent {
    return {
      title: '拼车拼房拼雪票，加入俱乐部社群更有专属福利！',
      path: '/pages/home/home'
    };
  }
});
